#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/3/21 17:53
# @Author  : 柳晓飞
# @Site    : 
# @File    : countTime.py
# @Software: PyCharm
#websocket client 参考下面地址
#https://pypi.python.org/pypi/websocket-client/
#计时器，每秒发送网络请求

import thread
import time
import sys
import websocket
import platform

sysstr = platform.system()
if(sysstr =="Windows"):
    sys.path.append('F:\pythonWork\JjServer\jjserver')
elif(sysstr == "Linux"):
    sys.path.append('/root/JjServer/jjserver')
else:
    print ("Other System no sys.path.append")

import net.protocal as protocal


def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        while True:
            time.sleep(1)
            try:
                ws.send('{"id":%d,"status":"ok"}'%protocal.tick)
            except Exception, e:
                print Exception, ":", e
                print '发送消息异常'
                break

    thread.start_new_thread(run, ())
def createWS():
    print '创建ws'
    ws = None
    while True:
        if None == ws or  None == ws.sock:
            print '循环创建ws'
            try:

                websocket.enableTrace(True)
                ws = websocket.WebSocketApp("ws://localhost:8091/jjserver",
                                            on_message=on_message,
                                            on_error=on_error,
                                            on_close=on_close)
                ws.on_open = on_open
                ws.run_forever()
            except Exception, e:
                print Exception, ":", e
                print '创建ws异常'
        time.sleep(3)


def startTick():
    thread.start_new_thread(createWS, ())

if __name__ == "__main__":
    startTick()
    while True:
        pass
    print('tick end')






